package com.cn.adapters;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cc.util.android.view.CCInnerListView;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.baidu.navi.activity.RouteGuideDemo;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.simu.constant.TableConstant.Collection;
import com.simu.towercrane.R;
import com.simu.towercrane.activity.ProductActivity;

public class ImageAndTextListAdapter extends BaseAdapter {
	private String IMG_FILD = "ImageURL";
	private int mResID;
	private List<Map<String, Object>> mList;
	private ListView mListView;
	private ArrayList<String> listImage;
	private ImageLoader mImageLoader;
	private ViewGroup group;
	private LayoutInflater mInflater;
	private String[] mFrom;
	private int[] mTo;
	private int count = 0;
	private Context mContext;
	private View viewcontext;
	private ImageListenr mImageListener;
	private Productdetils mProductdetils;
	private Map<String, Object> Mmap;
	private String userId;
//	private Boolean collected = false;
	private int IVheight = 200;
	private int IVwidth = 200;

	/*
	 * private int[] mInvokedIDs; private OnClickListener[] mListeners;
	 */

	private int mBackgroundResID = -1;
	private LinkedHashMap<String, SoftReference<Bitmap>> lruCache;

	public ImageAndTextListAdapter(Context context,
			List<Map<String, Object>> list, int resourceid, String[] from,
			int[] to) {
 
		mContext = context;
		SharedPreferences sharedPreferences = mContext.getSharedPreferences(
				"user", mContext.MODE_PRIVATE);
		userId = sharedPreferences.getString(Collection.userID, "0");
		this.mList = list;
		this.mResID = resourceid;
		this.mFrom = from;
		this.mTo = to;

		mImageLoader = ImageLoader.getInstance();
		this.mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		lruCache = new LinkedHashMap<String, SoftReference<Bitmap>>(20, 0.75f,
				true) {
			private static final long serialVersionUID = -2920787383821401845L;

			@Override
			protected boolean removeEldestEntry(
					java.util.Map.Entry<String, SoftReference<Bitmap>> eldest) {
				boolean remove = size() > 20;
				if (remove) {
					SoftReference<Bitmap> soft = eldest.getValue();
					soft.clear();
				}
				return remove;
			}
		};
	}

	public void setListView(ListView listView) {
		this.mListView = listView;
	}

	public void setItemBackgroud(int resID) {
		this.mBackgroundResID = resID;
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Deprecated
	public void setImgFild(String fild) {
		this.IMG_FILD = fild;
	}

	/*
	 * public void notifyCancelLoadImage() { mImageLoader.cancel(true); }
	 */

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = null;

		if (mListView instanceof CCInnerListView) {
			v = mInflater.inflate(mResID, parent, false);

		} else {
			if (convertView == null) {
				v = mInflater.inflate(mResID, parent, false);
				viewcontext = v;
			} else {
				v = convertView;
				viewcontext = v;
			}
		}

		ImageView ivHeightAndWidth = (ImageView) v
				.findViewById(R.id.IV_hight_width);

		if (ivHeightAndWidth != null) {
			LayoutParams para;
			para = ivHeightAndWidth.getLayoutParams();
			IVheight = para.height;
			IVwidth = para.width;
		}
		bindView(mList.get(position), v);
		if (mBackgroundResID != -1)
			v.setBackgroundResource(mBackgroundResID);
		return v;
	}

	public void invokeListener(int[] ids, OnClickListener[] listeners) {
		/*
		 * this.mInvokedIDs = ids; this.mListeners = listeners;
		 */
	}

	@SuppressWarnings("unchecked")
	private void bindView(final Map<String, Object> map, View v) {
		// Mmap=map;

		String id = map.get("objectID") + "";
		String tel = map.get("tel") + "";
//		if ((map.get("collected") + "").equals("collected")) {
//			collected = true;
//		}

		listImage = (ArrayList<String>) map.get("url");
		final int length = mFrom.length;
		if (listImage != null) {

			ViewGroup group = (ViewGroup) v.findViewById(R.id.viewGroup);
			group.removeAllViews();
			ImageView[] imageViews = new ImageView[listImage.size()];
			for (int i = 0; i < imageViews.length; i++) {
				final ImageView imageView = new ImageView(mContext);

				imageView.setLayoutParams(new LayoutParams(IVwidth, IVheight));
				imageView.setPadding(20, 0, 0, 0);

				imageViews[i] = imageView;
				ImageLoader.getInstance().displayImage(listImage.get(i) + "",
						imageViews[i]);
				imageViews[i].setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						if (mImageListener != null) {
							mImageListener.responeImageListner(imageView);
						}
					}
				});
				group.addView(imageView);

			}

		}

		for (int i = 0; i < length; i++) {
			final View view = v.findViewById(mTo[i]);
			if (view != null) {
				// 根据返回的数据的编码方式不同而不同
				Object data = map.get(mFrom[i]);
				String dataDe = data + "";
				if (view instanceof TextView) {

					((TextView) view).setText(dataDe);
					if (view.getId() == R.id.Resellname_ershou) {
						view.setOnClickListener(new SkipListener(id) {

							@Override
							public void onClick(View arg0) {

								// Bundle bundle = new Bundle();
								// bundle.putString("objectID",
								// Mmap.get("objectID")+"");
								// Intent intent = new Intent();
								// intent.setClass(mContext,
								// ProductFragment.class);
								//
								// intent.putExtra("objectID",
								// Mmap.get("objectID")+"");
								// mContext.startActivity(intent);

								Intent intent = new Intent();
								intent.setClass((Activity) mContext,
										ProductActivity.class);
								intent.putExtra("objectID", getId());
								mContext.startActivity(intent);

							}
						});
					}
					if (view.getId() == R.id.Resellclloction)

					{
						if ((map.get("collected") + "").equals("collected")) {
							((TextView) view).setText("取消");
						} else {

							((TextView) view).setText("收藏");
						}

						view.setOnClickListener(new SkipListener(id) {
							@Override
							public void onClick(View arg0) {

								AVUser user = AVUser.getCurrentUser();

								AVRelation<AVObject> relation = user
										.getRelation("watchedCommodity");
								AVQuery<AVObject> avQuery = relation.getQuery();

								if ((map.get("collected") + "").equals("collected")) {
									relation.remove(AVObject.createWithoutData(
											"Commodity", getId()));
									new AlertDialog.Builder(mContext)
											.setTitle("收藏")
											.setMessage("您已取消收藏！")
											.setPositiveButton("确定", null)
											.show();
									((TextView) view).setText("收藏");
									map.put("collected", "notcollected");
								} else {
									relation.add(AVObject.createWithoutData(
											"Commodity", getId()));
									new AlertDialog.Builder(mContext)
											.setTitle("收藏").setMessage("收藏成功！")
											.setPositiveButton("确定", null)
											.show();
									((TextView) view).setText("取消");
									map.put("collected", "collected");

								}
								user.saveInBackground();

								// AVUser query;
								// query = new AVUser();
								// query.
								// //query.whereEqualTo("objectId", userId);
								// query.findInBackground(new
								// FindCallback<AVObject>() {
								//
								// @Override
								// public void done(List<AVObject> list,
								// AVException arg1) {
								// // TODO Auto-generated method stub
								// AVObject parent = list.get(0);
								// //parent.getString("vendorName");
								//
								// AVRelation<AVObject> avRelation = parent
								// .getRelation("watcheCommodity");
								// AVQuery<AVObject> avQuery =
								// avRelation.getQuery();
								// avRelation.add(AVObject.createWithoutData("Commodity",getId()));
								//
								// }
								// });

							}
						});

					}
					if(view.getId() == R.id.Resellshare)
					{
						view.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								ArrayList<String> listImageurl = (ArrayList<String>) map.get("url");
								String url=listImageurl.get(0);
								Intent intWX = new Intent("android.intent.action.WXactivity");
								intWX.putExtra("url", url);
								mContext.startActivity(intWX);
							}
						});
					}
					if (view.getId() == R.id.Reselllocation) {
						view.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
			
								Intent intent = new Intent();
								intent.setClass((Activity) mContext,
										RouteGuideDemo.class);
								intent.putExtra("startlatitude",map.get("latitude")+"");
								intent.putExtra("startlongitude",map.get("longitude")+"" );
								intent.putExtra("endlatitude", map.get("latitudeproduct")+"");
								intent.putExtra("endlongitude", map.get("longitudeproduct")+"");
								intent.putExtra("startName", map.get("addr")+"");
								intent.putExtra("endNamge",map.get("address")+"");
								// intent.putExtra("objectID", getId());
								mContext.startActivity(intent);
							}
						});
					}

				} else if (view instanceof ImageView) {

					if (view.getId() == R.id.ResellconnectImg) {
						view.setOnClickListener(new SkipListener(tel) {

							@Override
							public void onClick(View arg0) {

								Intent intent = new Intent(Intent.ACTION_CALL,
										Uri.parse("tel:" + getId()));
								mContext.startActivity(intent);

							}
						});

					}

					else {
						if (view.getId() == R.id.ReselltitlecertifiedInfo) {
							if (map.get("iscertifiedInfo").equals(
									"certifiedInfo"))
								view.setVisibility(View.VISIBLE);

						} else {
							if (!dataDe.equals("")) {
								Log.d("img", dataDe);
							}
							// dataDe="http://www.cncfzx.com"+dataDe;
							ImageView imageView = (ImageView) view;
							imageView.setTag(dataDe + "");
							SoftReference<Bitmap> soft = lruCache.get(dataDe
									+ "");
							Bitmap bitmap = soft == null ? null : soft.get();
							if (bitmap != null) {
								// imageView.setImageBitmap(bitmap);
								BitmapDrawable bt = new BitmapDrawable(bitmap);
								imageView.setBackgroundDrawable(bt);
							} else {
								// imageView.setImageResource(R.drawable.def_img);
								imageView.setBackgroundDrawable(mContext
										.getResources().getDrawable(
												R.drawable.ic_stub));
								// mImageLoader.loadImage(dataDe + "",
								// imageView);
								mImageLoader.displayImage(dataDe + "",
										imageView);
							}
						}
					}
				} else {
					Log.e("error", v.getClass().getName() + " is not a "
							+ " view that can be bounds by this SimpleAdapter");
				}
			}

		}
		/*
		 * for (int i = 0; i < mInvokedIDs.length; i++) { View view =
		 * v.findViewById(mInvokedIDs[i]);
		 * view.setOnClickListener(mListeners[i]); }
		 */
	}

	public void setImageListener(ImageListenr iamgeListner) {
		this.mImageListener = iamgeListner;
	}

	public interface ImageListenr {
		public void responeImageListner(ImageView imageView);
	}

	public void setProductdetils(Productdetils productdetils) {

		this.mProductdetils = productdetils;
	}

	public interface Productdetils {
		public void responeProductdetils(String string);
	}

	class SkipListener implements OnClickListener {
		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		private String id;

		public SkipListener(String id) {
			this.id = id;
		}

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub

		}

	}
}
